import xlsxwriter


def create_table_content(search_list, content, location, red_format):
    search_list = list(set(search_list))

    for search_word in search_list:
        content = content.replace(search_word, "|||||" + search_word + "|||||")

    new_content = []
    new_content.append(location)
    for i in range(len(content.split("|||||"))):
        if content.split("|||||")[i]:
            if i % 2 == 1:
                new_content.append(red_format)
                new_content.append(content.split("|||||")[i])
            else:
                new_content.append(content.split("|||||")[i])
    return new_content


def save_excel(index, contentses, biaodian_list, word_sizes):
    # 创建一个新的Excel文件并添加一个工作表
    workbook = xlsxwriter.Workbook('问题{}.xlsx'.format(int(index + 1)))
    worksheet = workbook.add_worksheet()
    # 创建一个富文本格式对象
    red_format = workbook.add_format({'font_color': 'red'})  # 你可以设置其他属性，如粗体
    wrap_format = workbook.add_format({'text_wrap': True})  # 你可以设置其他属性，如粗体

    # url_format = workbook.get_default_url_format()

    for location, search_list, content in contentses:
        new_content = create_table_content(search_list, content, location, red_format)
        new_content = [i for i in new_content if i]
        worksheet.write_rich_string(*new_content)

    for i in range(len(biaodian_list)):
        worksheet.write_string(i, 2, str(biaodian_list[i]))
    for i in range(len(word_sizes)):
        worksheet.write_string(i, 3, str(word_sizes[i]))
    # worksheet.set_column('A:B', 256 * 20)
    worksheet.set_column(0, 1, 100, cell_format=wrap_format)  # 设置列宽
    worksheet.set_column(2, 3, 10, cell_format=wrap_format)  # 设置列宽

    # 关闭工作簿，输出Excel文件
    workbook.close()


from chinese_split_word_ictclas import new_table_data

for index in new_table_data:
    excel_data, biaodian_list, word_sizes = new_table_data[index]
    contentses = excel_data
    save_excel(index, contentses, biaodian_list, word_sizes)
